package com.mz.mattress.api.util;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.concurrent.ThreadLocalRandom;

@Slf4j
public class FileTool {

    static final BASE64Decoder decoder = new BASE64Decoder();

    public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyMMddHHmmss");

    /**
     * base64 编码转换为 BufferedImage
     * @param base64
     * @return
     */
    public static BufferedImage base64ToBufferedImage(String base64) {
        Base64.Decoder decoder = Base64.getDecoder();
        try {
            byte[] bytes1 = decoder.decode(base64);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            return ImageIO.read(bais);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String generateFileName(String ext) {
        return FORMATTER.format(LocalDateTime.now()) + (100 + ThreadLocalRandom.current().nextInt(899)) + "." + ext;
    }

    /**
     * base64数据转成文件保存到本地
     * @param base64String
     * @param filePath
     * @param ext
     * @return
     */
    public static String base64ToFile(String base64String, String filePath, String ext) {
        try {
            if (base64String == null || base64String.length() == 0) {
                return null;
            }

            byte[] bytes = decoder.decodeBuffer(base64String);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            String fileName = generateFileName(ext);
            fileName = DateUtil.getNowMonth() + "/" + fileName;
            String path = filePath + fileName;
            // getCanonicalFile 可解析正确各种路径
            File dest = new File(path).getCanonicalFile();
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            BufferedImage bi1 = ImageIO.read(bais);
            ImageIO.write(bi1, ext, dest);
            return fileName;
//            return path;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {

//        String idCardPath = "E:\\4.jpg";
//        String base64Img = IoUtils.getBase64Img(idCardPath);

    }
}
